<template>
  <div class="orders-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Tickets /></el-icon>
            <span>订单管理</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="订单状态">
            <el-select v-model="filters.status" placeholder="订单状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="待接单" value="waiting" />
              <el-option label="已接单" value="accepted" />
              <el-option label="进行中" value="inprogress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="filters.keyword" placeholder="订单号/乘客/司机" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchOrders">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单列表 -->
      <div class="orders-list">
        <el-table
          :data="ordersList"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="订单号" width="120" sortable />
          <el-table-column prop="passengerName" label="乘客" width="100" />
          <el-table-column prop="driverName" label="司机" width="100" />
          <el-table-column prop="startLocation" label="出发地" width="150" />
          <el-table-column prop="endLocation" label="目的地" width="150" />
          <el-table-column prop="createTime" label="创建时间" width="150" sortable />
          <el-table-column prop="amount" label="金额" width="100" sortable>
            <template #default="scope">
              ¥{{ scope.row.amount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 'waiting'" type="info">待接单</el-tag>
              <el-tag v-else-if="scope.row.status === 'accepted'" type="warning">已接单</el-tag>
              <el-tag v-else-if="scope.row.status === 'inprogress'" type="primary">进行中</el-tag>
              <el-tag v-else-if="scope.row.status === 'completed'" type="success">已完成</el-tag>
              <el-tag v-else-if="scope.row.status === 'cancelled'" type="danger">已取消</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                @click="showOrderDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button 
                size="small"
                type="danger"
                @click="cancelOrder(scope.row)"
                v-if="['waiting', 'accepted'].includes(scope.row.status)"
              >
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="700px"
    >
      <div class="order-detail" v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="currentOrder.status === 'waiting'" type="info">待接单</el-tag>
            <el-tag v-else-if="currentOrder.status === 'accepted'" type="warning">已接单</el-tag>
            <el-tag v-else-if="currentOrder.status === 'inprogress'" type="primary">进行中</el-tag>
            <el-tag v-else-if="currentOrder.status === 'completed'" type="success">已完成</el-tag>
            <el-tag v-else-if="currentOrder.status === 'cancelled'" type="danger">已取消</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="乘客">{{ currentOrder.passengerName }}</el-descriptions-item>
          <el-descriptions-item label="乘客电话">{{ currentOrder.passengerPhone }}</el-descriptions-item>
          <el-descriptions-item label="司机">{{ currentOrder.driverName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="司机电话">{{ currentOrder.driverPhone || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="出发地">{{ currentOrder.startLocation }}</el-descriptions-item>
          <el-descriptions-item label="目的地">{{ currentOrder.endLocation }}</el-descriptions-item>
          <el-descriptions-item label="乘客数">{{ currentOrder.passengerCount }}人</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="接单时间" v-if="currentOrder.acceptTime">{{ currentOrder.acceptTime }}</el-descriptions-item>
          <el-descriptions-item label="完成时间" v-if="currentOrder.completeTime">{{ currentOrder.completeTime }}</el-descriptions-item>
          <el-descriptions-item label="金额">¥{{ currentOrder.amount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag type="success" v-if="currentOrder.payStatus === 'paid'">已支付</el-tag>
            <el-tag type="warning" v-else>未支付</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentOrder.status === 'completed' && currentOrder.rating">
          <el-divider>乘客评价</el-divider>
          <div class="rating-info">
            <div class="rating-score">
              <span class="label">评分：</span>
              <el-rate v-model="currentOrder.rating" disabled show-score text-color="#ff9900"></el-rate>
            </div>
            <div class="rating-comment" v-if="currentOrder.comment">
              <span class="label">评价内容：</span>
              <div class="comment-text">{{ currentOrder.comment }}</div>
            </div>
          </div>
        </div>
        
        <div v-if="currentOrder.status === 'cancelled' && currentOrder.cancelReason">
          <el-divider>取消原因</el-divider>
          <div class="cancel-reason">
            <span class="label">取消原因：</span>
            <span>{{ currentOrder.cancelReason }}</span>
          </div>
          <div class="cancel-time">
            <span class="label">取消时间：</span>
            <span>{{ currentOrder.cancelTime }}</span>
          </div>
          <div class="cancel-by">
            <span class="label">取消方：</span>
            <span>{{ currentOrder.cancelBy }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="danger" 
            @click="handleCancelInDialog"
            v-if="currentOrder && ['waiting', 'accepted'].includes(currentOrder.status)"
          >
            取消订单
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="500px"
    >
      <div class="cancel-form" v-if="currentOrder">
        <el-form :model="cancelForm" label-width="100px">
          <el-form-item label="订单信息">
            <div>订单号: {{ currentOrder.id }}</div>
            <div>乘客: {{ currentOrder.passengerName }}</div>
          </el-form-item>
          <el-form-item label="取消原因" prop="reason">
            <el-select v-model="cancelForm.reason" placeholder="请选择取消原因">
              <el-option label="乘客无法联系" value="passenger_unreachable" />
              <el-option label="司机无法联系" value="driver_unreachable" />
              <el-option label="系统错误" value="system_error" />
              <el-option label="行程异常" value="trip_exception" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注说明" v-if="cancelForm.reason === 'other'">
            <el-input
              v-model="cancelForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入取消原因"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCancel">确认取消订单</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filters = reactive({
  status: '',
  dateRange: [],
  keyword: ''
})

// 重置筛选条件
const resetFilters = () => {
  filters.status = ''
  filters.dateRange = []
  filters.keyword = ''
  searchOrders()
}

// 搜索订单
const searchOrders = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API
    loading.value = false
    ElMessage.success('搜索完成')
  }, 500)
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  fetchOrdersList()
}

// 订单数据
const ordersList = ref([
  {
    id: 'O2023051001',
    passengerName: '李同学',
    passengerPhone: '13900001111',
    driverName: '张师傅',
    driverPhone: '13800001111',
    startLocation: '校园北门',
    endLocation: '火车站',
    createTime: '2023-05-10 08:00',
    acceptTime: '2023-05-10 08:05',
    completeTime: '2023-05-10 08:40',
    passengerCount: 1,
    amount: 25.5,
    status: 'completed',
    payStatus: 'paid',
    rating: 4.5,
    comment: '司机很准时，服务态度很好！'
  },
  {
    id: 'O2023051002',
    passengerName: '王同学',
    passengerPhone: '13900002222',
    driverName: '李师傅',
    driverPhone: '13800002222',
    startLocation: '图书馆',
    endLocation: '华联商场',
    createTime: '2023-05-10 09:30',
    acceptTime: '2023-05-10 09:35',
    completeTime: null,
    passengerCount: 2,
    amount: 18.0,
    status: 'inprogress',
    payStatus: 'paid'
  },
  {
    id: 'O2023051003',
    passengerName: '张同学',
    passengerPhone: '13900003333',
    driverName: null,
    driverPhone: null,
    startLocation: '学生公寓',
    endLocation: '市中心',
    createTime: '2023-05-10 10:15',
    acceptTime: null,
    completeTime: null,
    passengerCount: 3,
    amount: 30.0,
    status: 'waiting',
    payStatus: 'paid'
  },
  {
    id: 'O2023051004',
    passengerName: '赵同学',
    passengerPhone: '13900004444',
    driverName: '王师傅',
    driverPhone: '13800003333',
    startLocation: '艺术学院',
    endLocation: '科技园',
    createTime: '2023-05-10 11:00',
    acceptTime: '2023-05-10 11:05',
    completeTime: null,
    passengerCount: 1,
    amount: 22.0,
    status: 'accepted',
    payStatus: 'paid'
  },
  {
    id: 'O2023050901',
    passengerName: '陈同学',
    passengerPhone: '13900005555',
    driverName: '孙师傅',
    driverPhone: '13800004444',
    startLocation: '工学院',
    endLocation: '东湖公园',
    createTime: '2023-05-09 14:30',
    acceptTime: '2023-05-09 14:35',
    completeTime: null,
    passengerCount: 2,
    amount: 28.0,
    status: 'cancelled',
    payStatus: 'paid',
    cancelReason: '司机临时有事',
    cancelTime: '2023-05-09 14:50',
    cancelBy: '司机'
  }
])

// 计算总数
total.value = ordersList.value.length

// 获取订单列表数据
const fetchOrdersList = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API
    loading.value = false
  }, 500)
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrdersList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrdersList()
}

// 订单详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref(null)

// 显示订单详情
const showOrderDetail = (order) => {
  currentOrder.value = order
  detailDialogVisible.value = true
}

// 取消订单对话框
const cancelDialogVisible = ref(false)
const cancelForm = reactive({
  reason: '',
  remark: ''
})

// 取消订单
const cancelOrder = (order) => {
  currentOrder.value = order
  cancelForm.reason = ''
  cancelForm.remark = ''
  cancelDialogVisible.value = true
}

// 从详情对话框取消订单
const handleCancelInDialog = () => {
  detailDialogVisible.value = false
  cancelOrder(currentOrder.value)
}

// 提交取消
const submitCancel = () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请选择取消原因')
    return
  }
  
  if (cancelForm.reason === 'other' && !cancelForm.remark.trim()) {
    ElMessage.warning('请输入取消说明')
    return
  }
  
  // 模拟API请求
  // 在实际项目中，应该调用API提交取消订单
  
  // 更新订单状态
  if (currentOrder.value) {
    currentOrder.value.status = 'cancelled'
    currentOrder.value.cancelReason = cancelForm.reason === 'other' ? cancelForm.remark : getCancelReasonText(cancelForm.reason)
    currentOrder.value.cancelTime = new Date().toLocaleString()
    currentOrder.value.cancelBy = '管理员'
    
    // 更新列表中的订单状态
    const orderIndex = ordersList.value.findIndex(o => o.id === currentOrder.value.id)
    if (orderIndex !== -1) {
      ordersList.value[orderIndex].status = 'cancelled'
    }
    
    ElMessage.success('订单已取消')
    cancelDialogVisible.value = false
  }
}

// 获取取消原因文本
const getCancelReasonText = (reasonCode) => {
  const reasons = {
    'passenger_unreachable': '乘客无法联系',
    'driver_unreachable': '司机无法联系',
    'system_error': '系统错误',
    'trip_exception': '行程异常',
    'other': '其他原因'
  }
  return reasons[reasonCode] || reasonCode
}

// 组件挂载后执行
onMounted(() => {
  fetchOrdersList()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.orders-list {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.rating-info, .cancel-reason, .cancel-time, .cancel-by {
  margin-top: 10px;
}

.label {
  font-weight: bold;
  color: #606266;
}

.comment-text {
  margin-top: 5px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
}
</style> 